import React, { useState, Component } from "react"

function PromiseStudy() {
    const username = '韦小玉'
    const [count, setCount] = useState(0)
    const url: String = 'https://t7.baidu.com/it/u=1819248061,230866778&fm=193&f=GIF'

    // 加载图片
    const preloadImage = function (path) {
        console.log('执行加载图片方法--path--', path)
        return new Promise(function (resolve, reject) {
            const image = new Image()
            image.onload = resolve
            image.onerror = reject
            image.src = path
        })
    }
    console.log('preloadImage方法执行结果', preloadImage(url))

    // 此种执行会将同步函数，放到循环末尾执行
    const f1 = () => { console.log('now1') }
    Promise.resolve().then(f1)
    console.log('next1')

    /* 需求：让同步函数同步执行，异步函数异步执行，并使之具有统一api；两种实现方式
    *1.async函数
    2.new Promise
    让同步方法同步执行均用到了匿名立执行函数，加之需求很常见，有一个提案
    Promise.try()代替
    */
    // 法一
    const f2 = () => { console.log('now2') }
    (async () => f2())()
    console.log('next2')
    // 异步
    /*
    {
        (async () => f2())()
        .then()
        .catch()
    }
    */
    // 法二
    const f3 = () => { console.log('now3') }
    (
        () => new Promise(
            resolve => resolve(f3())
        )
    )()
    console.log('next3')
    // promise.try
    const f4 = () =>{ console.log('now4')}
    // Promise.try(f4)
    console.log('next4')



    return (
        <>
            <h1>Hello {username}</h1>
            {/* <button onClick={() => setCount((count) => count + 1)}>
            count is {count}
        </button> */}
        </>
    )
}
// class PromiseStudy extends Component {

//     render() {
//         const username = '韦小玉'

//         return (
//             <>
//                 <h1>Hello ${username}</h1>
//             </>
//         )
//     }
// }

export default PromiseStudy
